<template>
  <div class="trace-detail">
    <!-- 顶部信息区 -->
    <div class="top-info">
      <el-button style="float: right">导出溯源码</el-button>
      <el-button style="float: right">修改基本信息</el-button>

      <el-row gutter="24">
        <el-col :span="4">
          <el-image :src="productImg" class="main-img" fit="cover" />
        </el-col>
        <el-col :span="16">
          <div class="product-title">{{ baseInfo.productName }}</div>
          <el-row class="product-meta">
            <el-col :span="12">生产批次：{{ baseInfo.batch }}</el-col>
            <el-col :span="12">保质期：{{ baseInfo.expirationDate }} 天</el-col>
            <el-col :span="12">生产许可证号：{{ baseInfo.produceCode }}</el-col>
            <el-col :span="12">生产企业：{{ baseInfo.manufacturers }}</el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>

    <!-- 产品检验报告 -->
    <div class="section">
      <el-row>
        <el-col :span="4"> </el-col>
        <el-col :span="16">
          <div class="section-title">产品检验报告</div>
          <div class="img-list">
            <div v-for="(img, idx) in reportImgs" :key="idx" class="img-item">
              <el-image :src="img" class="img-thumb" fit="cover" />
              <el-icon class="img-delete" @click="removeImg(reportImgs, idx)"
                ><Close
              /></el-icon>
            </div>
            <!-- <el-upload
          class="img-upload"
          :show-file-list="false"
          :on-change="e => handleImgUpload(e, reportImgs)"
        >
          <div class="img-thumb img-upload-btn"><el-icon><Plus /></el-icon></div>
        </el-upload> -->
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- Tab栏 -->
    <el-tabs v-model="activeTab" class="tabs">
      <el-tab-pane label="养殖信息 (5/5)" name="farming">
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">养殖信息</span>
            <el-button size="small" class="section-btn" @click="openFarmingEdit"
              >设置</el-button
            >
          </div>
          <div class="farming-info-row">
            <div class="farming-info-col">
              <div class="info-item">
                <span class="info-label">品种：</span
                >{{ farmingInfo.breedName }}
              </div>
              <div class="info-item">
                <span class="info-label">饲养天数：</span
                >{{ farmingInfo.keepersDay }} 天
              </div>
              <div class="info-item">
                <span class="info-label">饲养负责人：</span
                >{{ farmingInfo.keepersPerson }}
              </div>
            </div>
            <div class="farming-info-col">
              <div class="info-item">
                <span class="info-label">来源：</span>{{ farmingInfo.origin }}
              </div>
              <div class="info-item">
                <span class="info-label">饲料品牌：</span
                >{{ farmingInfo.keepersBrand }}
              </div>
              <div class="info-item">
                <span class="info-label">出栏日期：</span
                >{{ farmingInfo.chuDateTime }}
              </div>
            </div>
          </div>
        </div>
        <!-- 保健信息表格 -->
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">保健信息</span>
            <el-button size="small" class="section-btn" @click="addHealthRow"
              >新增行</el-button
            >
          </div>
          <el-table
            :data="storageList"
            style="width: 1000px"
            class="health-table no-border-table"
          >
            <el-table-header>
              <tr>
                <th class="table-header">饲养天数</th>
                <th class="table-header">保健方式</th>
                <th class="table-header">保健方法</th>
                <th class="table-header">操作</th>
              </tr>
            </el-table-header>
            <el-table-column prop="keepersDay" label="饲养天数" width="120">
              <template #default="scope">
                <template v-if="scope.row._edit">
                  <el-input v-model="scope.row.keepersDay" size="small" />
                </template>
                <template v-else>
                  <span>{{ scope.row.keepersDay }}</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="immunityWay" label="保健方式" width="160">
              <template #default="scope">
                <template v-if="scope.row._edit">
                  <el-input v-model="scope.row.immunityWay" size="small" />
                </template>
                <template v-else>
                  <span>{{ scope.row.immunityWay }}</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="immunityMethod" label="保健方法" width="160">
              <template #default="scope">
                <template v-if="scope.row._edit">
                  <el-input v-model="scope.row.immunityMethod" size="small" />
                </template>
                <template v-else>
                  <span>{{ scope.row.immunityMethod }}</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <template v-if="scope.row._edit">
                  <el-button
                    type="primary"
                    size="small"
                    @click="saveRow(scope.row)"
                    >保存</el-button
                  >
                  <el-button size="small" @click="cancelEdit(scope.$index)"
                    >取消</el-button
                  >
                </template>
                <template v-else>
                  <el-button
                    type="primary"
                    size="small"
                    @click="editRow(scope.$index)"
                    >修改</el-button
                  >
                  <el-button
                    type="danger"
                    size="small"
                    @click="deleteRow(scope.$index)"
                    >删除</el-button
                  >
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 动检证 -->
        <div class="tab-section">
          <div class="section-title">动检证</div>
          <div class="img-list">
            <div v-for="(img, idx) in animalImgs" :key="idx" class="img-item">
              <el-image :src="img" class="img-thumb" fit="cover" />
              <el-icon class="img-delete" @click="removeImg(animalImgs, idx)"
                ><Close
              /></el-icon>
            </div>
            <!-- <el-upload
              class="img-upload"
              :show-file-list="false"
              :on-change="e => handleImgUpload(e, animalImgs)"
            >
              <div class="img-thumb img-upload-btn"><el-icon><Plus /></el-icon></div>
            </el-upload> -->
          </div>
        </div>
        <!-- 养殖企业信息 -->
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">企业信息</span>
            <el-button size="small" class="section-btn" @click="openCompanyEdit"
              >设置</el-button
            >
          </div>
          <div class="company-info-row">
            <div class="company-info-col">
              <div class="info-item">
                <span class="info-label">养殖场：</span
                >{{ companyInfo.yangName }}
              </div>
              <div class="info-item">
                <span class="info-label">存栏数量：</span
                >{{ companyInfo.cnumber }} 只
              </div>
            </div>
            <div class="company-info-col">
              <div class="info-item">
                <span class="info-label">负责人：</span
                >{{ companyInfo.headName }}
              </div>
            </div>
          </div>
        </div>
        <!-- 企业图片 -->
        <!-- <div class="tab-section">
          <div class="section-title">企业图片</div>
          <div class="img-list">
            <div v-for="(img, idx) in companyImgs" :key="idx" class="img-item">
              <el-image :src="img" class="img-thumb" fit="cover" />
              <el-icon class="img-delete" @click="removeImg(companyImgs, idx)"><Close /></el-icon>
            </div>
            <el-upload
              class="img-upload"
              :show-file-list="false"
              :on-change="e => handleImgUpload(e, companyImgs)"
            >
              <div class="img-thumb img-upload-btn"><el-icon><Plus /></el-icon></div>
            </el-upload>
          </div>
        </div> -->
      </el-tab-pane>
       <!-- 屠宰信息 -->
      <el-tab-pane label="屠宰信息 (5/5)" name="slaughter">
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">屠宰信息</span>
            <el-button
              size="small"
              class="section-btn"
              @click="openSlaughterEdit"
              >设置</el-button
            >
          </div>
          <el-row>
            <el-col :span="12">批次：{{ slaughterInfo.batch }}</el-col>
            <el-col :span="12"
              >到厂均重：{{ slaughterInfo.averageWeight }}</el-col
            >
            <el-col :span="12"
              >到厂时间：{{ slaughterInfo.daoDateTime }}</el-col
            >
            <el-col :span="12"
              >屠宰时间：{{ slaughterInfo.slaughterDateTime }}</el-col
            >
          </el-row>
        </div>
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">检疫证明</span>
          </div>
          <div class="img-list">
            <div
              v-for="(img, idx) in slaughterCertImgs"
              :key="idx"
              class="img-item"
            >
              <el-image :src="img" class="img-thumb" fit="cover" />
              <el-icon class="img-delete" @click="removeSlaughterCertImg(idx)"
                ><Close
              /></el-icon>
            </div>
            <el-upload
              class="img-upload"
              :show-file-list="false"
              :before-upload="beforeSlaughterCertUpload"
              :on-success="handleSlaughterCertSuccess"
              :action="slaughterCertUploadUrl"
            >
              <div class="img-thumb img-upload-btn">
                <el-icon><Plus /></el-icon>
              </div>
            </el-upload>
          </div>
        </div>
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">企业信息</span>
            <el-button
              size="small"
              class="section-btn"
              @click="openSlaughterCompanyEdit"
              >设置</el-button
            >
          </div>
          <el-row>
            <el-col :span="12"
              >公司名称：{{ slaughterCompanyInfo.companyName || '' }}</el-col
            >
            <el-col :span="12"
              >成立时间：{{ slaughterCompanyInfo.steupDateTime || '' }}</el-col
            >
            <el-col :span="24"
              >公司地址：{{ slaughterCompanyInfo.province || '' }}{{ slaughterCompanyInfo.city || '' }}{{ slaughterCompanyInfo.county || '' }}</el-col
            >
            <el-col :span="24"
              >公司简介：{{ slaughterCompanyInfo.companyProfile || '' }}</el-col
            >
          </el-row>
        </div>
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">企业照片</span>
          </div>
          <div class="img-list">
            <div
              v-for="(img, idx) in slaughterCompanyImgs"
              :key="idx"
              class="img-item"
            >
              <el-image :src="img" class="img-thumb" fit="cover" />
              <el-icon
                class="img-delete"
                @click="removeSlaughterCompanyImg(idx)"
                ><Close
              /></el-icon>
            </div>
            <el-upload
              class="img-upload"
              :show-file-list="false"
              :before-upload="beforeSlaughterCompanyUpload"
              :on-success="handleSlaughterCompanySuccess"
              :action="slaughterCompanyUploadUrl"
            >
              <div class="img-thumb img-upload-btn">
                <el-icon><Plus /></el-icon>
              </div>
            </el-upload>
          </div>
        </div>
      </el-tab-pane>
      <!-- 深加工信息 -->
      <el-tab-pane label="深加工信息 (5/5)" name="deep">
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">深加工信息</span>
            <el-button size="small" class="section-btn" @click="openDeepEdit"
              >设置</el-button
            >
          </div>
          <el-row>
            <el-col :span="12">班组：{{ deepInfo.team }}</el-col>
            <el-col :span="12">负责人：{{ deepInfo.headerName }}</el-col>
          </el-row>
        </div>
        <!-- 食品安全信息 -->
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">食品安全信息</span>
          </div>
          <div class="img-list">
            <div v-for="(img, idx) in deepSafeImgs" :key="idx" class="img-item">
              <el-image :src="img" class="img-thumb" fit="cover" />
              <el-icon class="img-delete" @click="removeDeepSafeImg(idx)"
                ><Close
              /></el-icon>
            </div>
            <el-upload
              class="img-upload"
              :show-file-list="false"
              :before-upload="beforeDeepSafeUpload"
              :on-success="handleDeepSafeSuccess"
              :action="deepSafeUploadUrl"
            >
              <div class="img-thumb img-upload-btn">
                <el-icon><Plus /></el-icon>
              </div>
            </el-upload>
          </div>
        </div>
        <!-- 供应商信息（循环渲染） -->
        <div
          v-for="(supplier, sIdx) in supplierList"
          :key="supplier.id"
          class="tab-section"
        >
          <div class="group-title">
            <span class="blue-title">供应商信息</span>
          </div>
          <div
            v-for="(item, iIdx) in supplier.items"
            :key="item.id"
            class="tab-section"
          >
            <div class="group-title">
              <span>{{ item.type }}</span>
              <el-button
                size="small"
                class="section-btn"
                @click="openMaterialEdit(sIdx, iIdx)"
                >设置</el-button
              >
            </div>
            <el-row>
              <el-col :span="12">生产批次：{{ item.batch }}</el-col>
            </el-row>
            <div class="group-title" style="margin-top: 8px">相关材料</div>
            <div class="img-list">
              <div
                v-for="(img, idx) in item.materialImgs"
                :key="idx"
                class="img-item"
              >
                <el-image :src="img" class="img-thumb" fit="cover" />
                <el-icon
                  class="img-delete"
                  @click="removeMaterialImg(sIdx, iIdx, idx)"
                  ><Close
                /></el-icon>
              </div>
              <el-upload
                class="img-upload"
                :show-file-list="false"
                :before-upload="
                  (file) => beforeMaterialUpload(file, sIdx, iIdx)
                "
                :on-success="(res) => handleMaterialSuccess(res, sIdx, iIdx)"
                :action="materialUploadUrl"
              >
                <div class="img-thumb img-upload-btn">
                  <el-icon><Plus /></el-icon>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
        <!-- 深加工企业信息 -->
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">企业信息</span>
            <el-button
              size="small"
              class="section-btn"
              @click="openDeepCompanyEdit"
              >设置</el-button
            >
          </div>
          <el-row>
            <el-col :span="12">公司名称：{{ deepCompanyInfo.name }}</el-col>
            <el-col :span="24"
              >生产许可证号：{{ deepCompanyInfo.license }}</el-col
            >
          </el-row>
        </div>
        <div class="tab-section">
          <div class="group-title">
            <span class="blue-title">企业照片</span>
          </div>
          <div class="img-list">
            <div
              v-for="(img, idx) in deepCompanyImgs"
              :key="idx"
              class="img-item"
            >
              <el-image :src="img" class="img-thumb" fit="cover" />
              <el-icon class="img-delete" @click="removeDeepCompanyImg(idx)"
                ><Close
              /></el-icon>
            </div>
            <el-upload
              class="img-upload"
              :show-file-list="false"
              :before-upload="beforeDeepCompanyUpload"
              :on-success="handleDeepCompanySuccess"
              :action="deepCompanyUploadUrl"
            >
              <div class="img-thumb img-upload-btn">
                <el-icon><Plus /></el-icon>
              </div>
            </el-upload>
          </div>
        </div>
        <!-- 生产批次设置弹窗 -->
        <el-dialog
          v-model="editMaterialDialog.visible"
          title="设置"
          width="400px"
        >
          <el-form :model="editMaterialDialog.form" label-width="100px">
            <el-form-item label="生产批次">
              <el-input v-model="editMaterialDialog.form.batch" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button type="primary" @click="saveMaterialBatch"
              >保存</el-button
            >
          </template>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>

    <!-- 养殖信息编辑弹窗 -->
    <el-dialog
      v-model="editFarmingDialog"
      title="养殖信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="farmingForm"
        :rules="farmingRules"
        ref="farmingFormRef"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="品种" prop="breedName">
          <el-input v-model="farmingForm.breedName" />
        </el-form-item>
        <el-form-item label="来源" prop="origin">
          <el-input v-model="farmingForm.origin" />
        </el-form-item>
        <el-form-item label="饲养天数" prop="keepersDay">
          <el-input v-model="farmingForm.keepersDay" />
        </el-form-item>
        <el-form-item label="饲料品牌" prop="keepersBrand">
          <el-input v-model="farmingForm.keepersBrand" />
        </el-form-item>
        <el-form-item label="饲养负责人" prop="keepersPerson">
          <el-input v-model="farmingForm.keepersPerson" />
        </el-form-item>
        <el-form-item label="出栏日期" prop="chuDateTime">
          <el-date-picker
            v-model="farmingForm.chuDateTime"
            type="date"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="onSaveFarming">保存</el-button>
      </template>
    </el-dialog>

    <!-- 养殖企业信息编辑弹窗 -->
    <el-dialog
      v-model="editCompanyDialog"
      title="企业信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="companyForm"
        :rules="companyRules"
        ref="companyFormRef"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="养殖场" prop="yangName" required>
          <el-input v-model="companyForm.yangName" />
        </el-form-item>
        <el-form-item label="负责人" prop="headName" required>
          <el-input v-model="companyForm.headName" />
        </el-form-item>
        <el-form-item label="存栏数量（只）" prop="cnumber" required>
          <el-input v-model="companyForm.cnumber" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="onSaveCompany">保存</el-button>
      </template>
    </el-dialog>

    <!-- 屠宰信息编辑弹窗 -->
    <el-dialog
      v-model="editSlaughterDialog"
      title="屠宰信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="slaughterForm"
        :rules="slaughterRules"
        ref="slaughterFormRef"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="批次" prop="batch" disabled>
          <el-input v-model="slaughterForm.batch" />
        </el-form-item>
        <el-form-item label="到厂均重（公斤）" prop="averageWeight" required>
          <el-input v-model="slaughterForm.averageWeight" />
        </el-form-item>
        <el-form-item label="到厂时间" prop="daoDateTime" required>
          <el-date-picker
            v-model="slaughterForm.daoDateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="屠宰时间" prop="slaughterDateTime" required>
          <el-date-picker
            v-model="slaughterForm.slaughterDateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="onSaveSlaughter">保存</el-button>
      </template>
    </el-dialog>

    <!--屠宰企业信息设置弹窗-->
    <el-dialog
      v-model="editSlaughterCompanyDialog"
      title="企业信息"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="slaughterCompanyForm"
        :rules="slaughterCompanyRules"
        ref="slaughterCompanyFormRef"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="公司名称" prop="companyName" required>
          <el-input v-model="slaughterCompanyForm.companyName" />
        </el-form-item>
        <el-form-item label="公司地址" required>
          <el-select
            v-model="slaughterCompanyForm.province"
            placeholder="请选择省"
            style="width: 120px; margin-right: 8px"
            @change="onSlaughterProvinceChange"
          >
            <el-option
              v-for="item in provinceList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
          <el-select
            v-model="slaughterCompanyForm.city"
            placeholder="请选择市"
            style="width: 120px; margin-right: 8px"
            @change="onSlaughterCityChange"
          >
            <el-option
              v-for="item in cityList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
          <el-select
            v-model="slaughterCompanyForm.district"
            placeholder="请选择区/县"
            style="width: 120px"
          >
            <el-option
              v-for="item in districtList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成立时间" prop="steupDateTime" required>
          <el-date-picker
            v-model="slaughterCompanyForm.steupDateTime"
            type="date"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="公司简介" prop="companyProfile">
          <el-input
            v-model="slaughterCompanyForm.companyProfile"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="onSaveSlaughterCompany"
          >保存</el-button
        >
      </template>
    </el-dialog>
    <!-- 深加工信息弹出框 -->
    <el-dialog
      v-model="editDeepDialog"
      title="企业信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="deepForm"
        :rules="deepRules"
        ref="companyFormRef"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="班组" prop="team" required>
          <el-input v-model="deepForm.team" />
        </el-form-item>
        <el-form-item label="负责人" prop="headerName" required>
          <el-input v-model="deepForm.headerName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="savedeep">保存</el-button>
      </template>
    </el-dialog>

    <!-- 深加工企业信息弹出框 -->
    <el-dialog
      v-model="editDeepCompanyDialog"
      title="企业信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="deepcompanyForm"
        :rules="deepcompanyRules"
        ref="companyFormRef"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="班组" prop="team" required>
          <el-input v-model="deepForm.team" />
        </el-form-item>
        <el-form-item label="负责人" prop="headerName" required>
          <el-input v-model="deepForm.headerName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="savedeep">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { Plus, Close } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import axios from "axios";
import { regionData } from "element-china-area-data";
import dayjs from "dayjs";
onMounted(() => {
  getdesc();
  getyang();
  getBao();
  getcompany();
  gettuzai();
  gettucompany();
  getshen();
});
const route = useRoute();
const productImg = ref();
const reportImgs = ref(["https://img.yzcdn.cn/vant/cat.jpeg"]);
const animalImgs = ref(["https://img.yzcdn.cn/vant/cat.jpeg"]);
const companyImgs = ref([
  "https://img.yzcdn.cn/vant/cat.jpeg",
  "https://img.yzcdn.cn/vant/cat.jpeg",
]);

var id = route.query.batch;
const baseInfo = ref({
  productName: "",
  batch: "",
  expirationDate: 0,
  produceCode: "",
  manufacturers: "",
});

const getdesc = () => {
  axios
    .get("https://localhost:7235/api/Traceability/GetBuTraceability", {
      params: { Batch: id },
    })
    .then((res) => {
      baseInfo.value = res.data.datas[0];
      productImg.value = res.data.datas[0].photo;
    });
};
//养殖信息弹出框
const editFarmingDialog = ref(false);
const farmingFormRef = ref();
//养殖信息添加修改数据源
const farmingForm = reactive({
  breedName: "",
  origin: "",
  keepersDay: "",
  keepersBrand: "",
  keepersPerson: "",
  chuDateTime: "",
  batch: id,
});
const farmingRules = {
  breedName: [{ required: true, message: "请输入品种", trigger: "blur" }],
  origin: [{ required: true, message: "请输入来源", trigger: "blur" }],
  keepersDay: [{ required: true, message: "请输入饲养天数", trigger: "blur" }],
  keepersBrand: [
    { required: true, message: "请输入饲料品牌", trigger: "blur" },
  ],
  keepersPerson: [{ required: true, message: "请输入负责人", trigger: "blur" }],
  chuDateTime: [
    { required: true, message: "请选择出栏日期", trigger: "change" },
  ],
};
//养殖信息反填数据
const farmingInfo = reactive({
  breedName: "",
  origin: "",
  keepersDay: "",
  keepersBrand: "",
  keepersPerson: "",
  chuDateTime: "",
  batch: "",
});

// 初始化弹窗表单数据
function openFarmingEdit() {
  Object.assign(farmingForm, farmingInfo);
  editFarmingDialog.value = true;
}
//反填养殖信息数据方法
const getyang = () => {
  axios
    .get("https://localhost:7235/api/Aquaculture/GetAquaculture", {
      params: { Batch: id },
    })
    .then((res) => {
      farmingInfo.breedName = res.data.data.breedName;
      farmingInfo.origin = res.data.data.origin;
      farmingInfo.keepersDay = res.data.data.keepersDay;
      farmingInfo.keepersBrand = res.data.data.keepersBrand;
      farmingInfo.keepersPerson = res.data.data.keepersPerson;
      farmingInfo.chuDateTime = res.data.data.chuDateTime;
      farmingInfo.batch = <any>id;
    });
};
//保存修改养殖信息
function onSaveFarming() {
  farmingFormRef.value.validate((valid: boolean) => {
    if (valid) {
      farmingForm.batch = id;
      axios
        .post(
          "https://localhost:7235/api/Aquaculture/AddAquaculture",
          farmingForm
        )
        .then((res) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
            editFarmingDialog.value = false;
            getyang();
          } else {
            ElMessage.error(res.data.msg);
          }
        });
    }
  });
}
//保健信息

const storageList = ref([{}]);
// getBao赋值时为每行加_edit:false
const getBao = () => {
  axios
    .get("https://localhost:7235/api/Aquaculture/GetBao", {
      params: { Batch: id },
    })
    .then((res) => {
      storageList.value = Array.isArray(res.data.data)
        ? res.data.data.map((item) => ({ ...item, _edit: false }))
        : [];
    });
};

// 新增一行
const addHealthRow = () => {
  storageList.value.push({
    keepersDay: "",
    immunityWay: "",
    immunityMethod: "",
    batch: id,
    _edit: true,
    // 不要有id字段
  });
};

// 修改
function editRow(index: any) {
  storageList.value[index]._edit = true;
}
// 取消
function cancelEdit(index: any) {
  // 新增行取消直接移除
  const row = storageList.value[index];
  if (!row.keepersDay && !row.immunityWay && !row.immunityMethod && !row.id) {
    storageList.value.splice(index, 1);
  } else {
    storageList.value[index]._edit = false;
  }
}
// 删除
function deleteRow(index: any) {
  const row = storageList.value[index];
  if (!row.id) {
    // 新增未保存的行，直接前端移除
    storageList.value.splice(index, 1);
    return;
  }
  // 已有数据，调用后端接口删除（PUT，id放body）
  axios
    .put("https://localhost:7235/api/Aquaculture/DelBao", { id: row.id })
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.msg || "删除成功");
        getBao(); // 刷新表格
      } else {
        ElMessage.error(res.data.msg || "删除失败");
      }
    })
    .catch(() => {
      ElMessage.error("删除失败");
    });
}
// 保存
function saveRow(row: any) {
  if (!row.keepersDay || !row.immunityWay || !row.immunityMethod) {
    ElMessage.error("请填写完整的保健信息");
    return;
  }
  row.batch = id;
  if (row.id) {
    // 有id，走修改
    axios
      .put("https://localhost:7235/api/Aquaculture/UpdateBao", row)
      .then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          row._edit = false;
          getBao();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
  } else {
    // 没有id，走新增
    axios
      .post("https://localhost:7235/api/Aquaculture/AddBao", row)
      .then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          getBao();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
  }
}

// el-table模板参考：
// <el-table :data="storageList" ...>
//   <el-table-column prop="keepersDay" label="饲养天数">
//     <template #default="scope">
//       <template v-if="scope.row._edit">
//         <el-input v-model="scope.row.keepersDay" size="small" />
//       </template>
//       <template v-else>
//         {{ scope.row.keepersDay }}
//       </template>
//     </template>
//   </el-table-column>
//   ...
//   <el-table-column label="操作">
//     <template #default="scope">
//       <template v-if="scope.row._edit">
//         <el-link type="primary" @click="saveRow(scope.row)">保存</el-link>
//         <el-link @click="cancelEdit(scope.$index)">取消</el-link>
//       </template>
//       <template v-else>
//         <el-link type="primary" @click="editRow(scope.$index)">修改</el-link>
//         <el-link type="danger" @click="deleteRow(scope.$index)">删除</el-link>
//       </template>
//     </template>
//   </el-table-column>
// </el-table>

//养殖企业信息反填数据源
const companyInfo = reactive({
  yangName: "",
  headName: "",
  cnumber: "",
  batch: id,
});
//反填养殖企业信息方法
const getcompany = () => {
  axios
    .get("https://localhost:7235/api/Aquaculture/GetYangCompany", {
      params: { Batch: id },
    })
    .then((res) => {
      companyInfo.cnumber = res.data.data.cnumber;
      companyInfo.headName = res.data.data.headName;
      companyInfo.yangName = res.data.data.yangName;
      companyInfo.batch = id;
    });
};
const activeTab = ref("farming");

//修改企业信息
const editCompanyDialog = ref(false);
const companyFormRef = ref();
//保存修改企业信息数据源
const companyForm = reactive({
  yangName: "",
  headName: "",
  cnumber: "",
  batch: id,
});
const companyRules = {
  yangName: [{ required: true, message: "请输入养殖场", trigger: "blur" }],
  headName: [{ required: true, message: "请输入负责人", trigger: "blur" }],
  cnumber: [{ required: true, message: "请输入存栏数量", trigger: "blur" }],
};
function removeImg(arr: any[], idx: number) {
  arr.splice(idx, 1);
}
//保存修改养殖企业信息方法
function onSaveCompany() {
  companyFormRef.value.validate((valid: any) => {
    if (valid) {
      companyForm.batch = id;
      axios
        .post(
          "https://localhost:7235/api/Aquaculture/UpdateAquacultureCompany",
          companyForm
        )
        .then((res) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
            editCompanyDialog.value = false;
            getcompany();
          } else {
            ElMessage.error(res.data.msg);
          }
        });
    }
  });
}
// 初始化弹窗表单数据
function openCompanyEdit() {
  Object.assign(companyForm, companyInfo);
  editCompanyDialog.value = true;
}

// 屠宰信息
const slaughterInfo = reactive({
  batch: id,
  averageWeight: "",
  daoDateTime: "",
  slaughterDateTime: "",
});

const gettuzai = () => {
  axios
    .get("https://localhost:7235/api/Slaughter/GetSlaughter", {
      params: { Batch: id },
    })
    .then((res) => {
      slaughterInfo.averageWeight = res.data.data.averageWeight;
      slaughterInfo.daoDateTime = res.data.data.daoDateTime;
      slaughterInfo.slaughterDateTime = res.data.data.slaughterDateTime;
      slaughterInfo.batch = <any>id;
    });
};
const slaughterCertImgs = ref([]);
const slaughterCertUploadUrl =
  "https://localhost:7235/api/File/UploadSlaughterCert";
function beforeSlaughterCertUpload(file: any) {
  const isImg = file.type.startsWith("image/");
  if (!isImg) ElMessage.error("只能上传图片");
  return isImg;
}
function handleSlaughterCertSuccess(res: any) {
  if (res.code === 200) {
    slaughterCertImgs.value.push(res.data.url);
  } else {
    ElMessage.error(res.msg);
  }
}
function removeSlaughterCertImg(idx: any) {
  slaughterCertImgs.value.splice(idx, 1);
}
//屠宰信息设置弹窗
const editSlaughterDialog = ref(false);
const slaughterFormRef = ref();
const slaughterForm = reactive({
  batch: id,
  averageWeight: "",
  daoDateTime: "",
  slaughterDateTime: "",
});
const slaughterRules = {
  batch: [{ required: true, message: "请输入批次", trigger: "blur" }],
  averageWeight: [
    { required: true, message: "请输入到厂均重", trigger: "blur" },
  ],
  daoDateTime: [
    { required: true, message: "请选择到厂时间", trigger: "change" },
  ],
  slaughterDateTime: [
    { required: true, message: "请选择屠宰时间", trigger: "change" },
  ],
};
function openSlaughterEdit() {
  // 反填当前屠宰信息
  Object.assign(slaughterForm, slaughterInfo);
  editSlaughterDialog.value = true;
}
//屠宰信息保存方法
function onSaveSlaughter() {
  slaughterFormRef.value.validate((valid) => {
    if (valid) {
      const payload = {
        batch: slaughterForm.batch,
        averageWeight: Number(slaughterForm.averageWeight),
        daoDateTime: dayjs(slaughterForm.daoDateTime).toISOString(),
        slaughterDateTime: dayjs(slaughterForm.slaughterDateTime).toISOString(),
      };
      axios
        .post("https://localhost:7235/api/Slaughter/AddSlaughter", payload)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.msg);
            editSlaughterDialog.value = false;
            // 刷新屠宰信息
          } else {
            ElMessage.error(res.data.msg);
          }
        });
    }
  });
}
// 屠宰企业信息
const slaughterCompanyInfo = reactive({
  companyName: "",
  steupDateTime: "",
  companyProfile: "",
  province: "",
  city: "",
  county: "",
  batch: ""
});
const gettucompany = () => {
  axios.get("https://localhost:7235/api/Slaughter/GetTuCompany", { params: { Batch: id } }).then((res) => {
    const data = res.data.data || {};
    slaughterCompanyInfo.city = data.city || "";
    slaughterCompanyInfo.companyName = data.companyName || "";
    slaughterCompanyInfo.steupDateTime = data.steupDateTime || "";
    slaughterCompanyInfo.companyProfile = data.companyProfile || "";
    slaughterCompanyInfo.province = data.province || "";
    slaughterCompanyInfo.county = data.county || "";
  });
};
const editSlaughterCompanyDialog = ref(false);
const slaughterCompanyFormRef = ref();
const slaughterCompanyForm = reactive({
  companyName: "",
  steupDateTime: "",
  companyProfile: "",
  province: "",
  city: "",
  county: "",
  batch:id
});
const slaughterCompanyRules = {
  companyName: [{ required: true, message: "请输入公司名称", trigger: "blur" }],
  province: [{ required: true, message: "请选择省", trigger: "change" }],
  city: [{ required: true, message: "请选择市", trigger: "change" }],
  county: [{ required: true, message: "请选择区/县", trigger: "change" }],
  steupDateTime: [{ required: true, message: "请选择成立时间", trigger: "change" }],
};
const provinceList = ref(
  regionData.map((i) => ({
    label: i.label,
    value: i.value,
    children: i.children,
  }))
);
const cityList :any = ref([]);
const districtList:any = ref([]);

function onSlaughterProvinceChange(val: any) {
  const province:any = regionData.find((i) => i.label === val);
  cityList.value = province
    ? province.children.map((i) => ({
        label: i.label,
        value: i.value,
        children: i.children,
      }))
    : [];
  slaughterCompanyForm.city = "";
  slaughterCompanyForm.district = "";
  districtList.value = [];
}
function onSlaughterCityChange(val: any) {
  const province = regionData.find(
    (i) => i.label === slaughterCompanyForm.province
  );
  const city = province?.children.find((i) => i.label === val);
  districtList.value = city
    ? city.children.map((i) => ({ label: i.label, value: i.value }))
    : [];
  slaughterCompanyForm.district = "";
}

function openSlaughterCompanyEdit() {
  Object.assign(slaughterCompanyForm, slaughterCompanyInfo);
  onSlaughterProvinceChange(slaughterCompanyForm.province);
  onSlaughterCityChange(slaughterCompanyForm.city);
  editSlaughterCompanyDialog.value = true;
}

function onSaveSlaughterCompany() {
  slaughterCompanyFormRef.value.validate((valid) => {
    if (valid) {
      let steupDateTime = '';
      if (slaughterCompanyForm.steupDateTime) {
        const dateObj = dayjs(slaughterCompanyForm.steupDateTime);
        if (dateObj.isValid()) {
          // 用完整ISO格式，兼容所有.NET后端
          steupDateTime = dateObj.toDate().toISOString();
        }
      }
      const payload = {
        companyName: slaughterCompanyForm.companyName,
        province: slaughterCompanyForm.province,
        city: slaughterCompanyForm.city,
        county: slaughterCompanyForm.county,
        steupDateTime: steupDateTime,
        companyProfile: slaughterCompanyForm.companyProfile,
        batch: id
      }
      console.log('payload', payload); // 打印实际发送内容
      axios.post('https://localhost:7235/api/Slaughter/AddSlaughterCompany', payload).then(res => {
        if (res.data.code === 200) {
          ElMessage.success(res.data.msg)
          editSlaughterCompanyDialog.value = false
          gettucompany();
        } else {
          ElMessage.error(res.data.msg)
        }
      })
    }
  })
}
const slaughterCompanyImgs = ref([]);
const slaughterCompanyUploadUrl =
  "https://localhost:7235/api/File/UploadSlaughterCompanyImg";
function beforeSlaughterCompanyUpload(file: any) {
  const isImg = file.type.startsWith("image/");
  if (!isImg) ElMessage.error("只能上传图片");
  return isImg;
}
function handleSlaughterCompanySuccess(res: any) {
  if (res.code === 200) {
    slaughterCompanyImgs.value.push(res.data.url);
  } else {
    ElMessage.error(res.msg);
  }
}
function removeSlaughterCompanyImg(idx: any) {
  slaughterCompanyImgs.value.splice(idx, 1);
}

// 深加工基本信息
const deepInfo = reactive({
  team: "",
  headerName: "",
});
const getshen=()=>{
  axios.get("https://localhost:7235/api/Deep/GetDeep",{params:{Batch:id}}).then(res=>{
    deepInfo.team=res.data.data.team;
    deepInfo.headerName=res.data.data.headerName;
  })
}
const  deepForm=reactive({
  "team": "",
  "headerName": "",
  "batch": id
})
const deepRules=({
   team: [{ required: true, message: "请输入班组名称", trigger: "blur" }],
  headerName: [{ required: true, message: "请输入负责人", trigger: "change" }],
})
const editDeepDialog=ref(false);
const openDeepEdit = () => {
  // 打开深加工信息编辑弹窗 
  Object.assign(deepForm,deepInfo);
  editDeepDialog.value=true;
};
const savedeep=()=>{
  axios.post("https://localhost:7235/api/Deep/AddDeep",deepForm).then(res=>{
    if(res.data.code==200){
      ElMessage.success(res.data.msg);
      editDeepDialog.value=false;
      getshen();
    }
    else{
      ElMessage.error(res.data.msg);
    }
  })
}

// 食品安全信息
const deepSafeImgs = ref([]);
const deepSafeUploadUrl = "https://localhost:7235/api/File/UploadDeepSafe";
function beforeDeepSafeUpload(file: any) {
  const isImg = file.type.startsWith("image/");
  if (!isImg) ElMessage.error("只能上传图片");
  return isImg;
}
function handleDeepSafeSuccess(res: any) {
  if (res.code === 200) {
    deepSafeImgs.value.push(res.data.url);
  } else {
    ElMessage.error(res.msg);
  }
}
function removeDeepSafeImg(idx: any) {
  deepSafeImgs.value.splice(idx, 1);
}
// 供应商信息（示例结构，实际请用接口数据）
const supplierList = ref([
  {
    id: 1,
    items: [
      { id: 11, type: "原料", batch: "20230701", materialImgs: [] },
      { id: 12, type: "辅料", batch: "20230701", materialImgs: [] },
      { id: 13, type: "添加剂", batch: "20230701", materialImgs: [] },
    ],
  },
  // 可有多个供应商
]);
const materialUploadUrl = "https://localhost:7235/api/File/UploadMaterial";
function beforeMaterialUpload(file: any, sIdx: any, iIdx: any) {
  const isImg = file.type.startsWith("image/");
  if (!isImg) ElMessage.error("只能上传图片");
  return isImg;
}
function handleMaterialSuccess(res: any, sIdx: any, iIdx: any) {
  if (res.code === 200) {
    supplierList.value[sIdx].items[iIdx].materialImgs.push(res.data.url);
  } else {
    ElMessage.error(res.msg);
  }
}
function removeMaterialImg(sIdx: any, iIdx: any, idx: any) {
  supplierList.value[sIdx].items[iIdx].materialImgs.splice(idx, 1);
}
// 设置弹窗
const editMaterialDialog = reactive({
  visible: false,
  sIdx: null,
  iIdx: null,
  form: { batch: "" },
});
function openMaterialEdit(sIdx: any, iIdx: any) {
  editMaterialDialog.sIdx = sIdx;
  editMaterialDialog.iIdx = iIdx;
  editMaterialDialog.form.batch = supplierList.value[sIdx].items[iIdx].batch;
  editMaterialDialog.visible = true;
}
function saveMaterialBatch() {
  if (editMaterialDialog.sIdx !== null && editMaterialDialog.iIdx !== null) {
    supplierList.value[editMaterialDialog.sIdx].items[
      editMaterialDialog.iIdx
    ].batch = editMaterialDialog.form.batch;
  }
  editMaterialDialog.visible = false;
}
// 深加工企业信息
const deepCompanyInfo = reactive({
  name: "",
  foundDate: "",
  address: "",
  intro: "",
  license: "",
});
const deepCompanyImgs = ref([]);
const deepCompanyUploadUrl =
  "https://localhost:7235/api/File/UploadDeepCompanyImg";
function beforeDeepCompanyUpload(file: any) {
  const isImg = file.type.startsWith("image/");
  if (!isImg) ElMessage.error("只能上传图片");
  return isImg;
}
function handleDeepCompanySuccess(res: any) {
  if (res.code === 200) {
    deepCompanyImgs.value.push(res.data.url);
  } else {
    ElMessage.error(res.msg);
  }
}
function removeDeepCompanyImg(idx: any) {
  deepCompanyImgs.value.splice(idx, 1);
}
const editDeepCompanyDialog=ref(false);
const deepcompanyForm=ref({
  
})
const deepcompanyRules=({

})
const openDeepCompanyEdit = () => {
  // 打开深加工企业信息编辑弹窗
};
</script>

<style scoped>
.trace-detail {
  background: #fff;
  padding: 32px 32px 24px 32px;
  border-radius: 8px;
  margin: 24px;
}
.top-info {
  margin-bottom: 16px;
}
.main-img {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  object-fit: cover;
  border: 1px solid #eee;
}
.product-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}
.product-meta {
  font-size: 15px;
  color: #333;
  margin-bottom: 8px;
}
.top-btns {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 12px;
  margin-top: 8px;
}
.section {
  margin-bottom: 24px;
}
.section-title {
  font-weight: bold;
  margin-bottom: 8px;
  font-size: 16px;
}
.section-title.with-btn {
  display: flex;
  align-items: center;
  gap: 8px;
}
.section-btn {
  margin-left: 8px;
}
.img-list {
  display: flex;
  align-items: center;
  gap: 16px;
}
.img-item {
  position: relative;
}
.img-thumb {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
  border: 1px solid #eee;
  background: #fafafa;
}
.img-upload {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background: #fafafa;
}
.img-upload-btn {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  color: #bbb;
  border-radius: 4px;
  border: 1px dashed #d9d9d9;
  background: #fafafa;
}
.img-delete {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  font-size: 18px;
  color: #f56c6c;
  z-index: 2;
}
.tab-section {
  margin-bottom: 24px;
}
.tabs {
  margin-top: 16px;
}
.group-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}
.blue-title {
  color: #1976d2;
  font-weight: bold;
  font-size: 16px;
}
.farming-info-row {
  display: flex;
  gap: 48px;
  margin-bottom: 16px;
}
.farming-info-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.info-item {
  font-size: 15px;
  color: #222;
  margin-bottom: 2px;
}
.info-label {
  color: #888;
  min-width: 80px;
  display: inline-block;
}
.health-table ::v-deep .el-table__header th {
  background: #f5f6fa;
  color: #222;
  font-weight: bold;
  text-align: left;
}
.health-table ::v-deep .el-table__cell {
  text-align: left;
}
.no-border-table ::v-deep .el-table__inner-wrapper,
.no-border-table ::v-deep .el-table__body,
.no-border-table ::v-deep .el-table__header {
  border: none !important;
}
.no-border-table ::v-deep th,
.no-border-table ::v-deep td {
  border-bottom: none !important;
  border-right: none !important;
}
.company-info-row {
  display: flex;
  gap: 48px;
  margin-bottom: 16px;
}
.company-info-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
</style>
